package com.inspur.security.cbb3.kms.keymanager.adminManager.service.impl;

import com.inspur.security.cbb3.kms.exception.UserInfoInVaildException;
import com.inspur.security.cbb3.kms.keymanager.adminManager.service.AdminManagerService;
import com.inspur.security.cbb3.kms.keymanager.secrets.po.SecretsBean;
import com.inspur.security.cbb3.kms.keymanager.secrets.repository.SecretsRepository;
import com.inspur.security.cbb3.kms.sysuser.po.SysUserBean;
import com.inspur.security.cbb3.kms.sysuser.service.SysUserService;
import com.inspur.security.cbb3.kms.utils.PageRequestDate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.MissingServletRequestParameterException;

import javax.persistence.criteria.Predicate;
import javax.validation.ValidationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * AdminManagerServiceImpl
 *
 * @author liukai
 * @date 2020/12/3
 **/
@Service
@Transactional(readOnly = true)
public class AdminManagerServiceImpl implements AdminManagerService {

    @Autowired
    private SecretsRepository secretsRepository;

    @Autowired
    private SysUserService sysUserService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cleanupAllLogicalDelKey() {
        //权限校验
        checkPermission();
        secretsRepository.deleteByDeleted(true);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cleanupLogicalDelKey(String uuid){
        //参数校验
        if (StringUtils.isEmpty(uuid)){
            throw new ValidationException("密钥不存在");
        }
        Optional<SecretsBean> optional = secretsRepository.findById(uuid);
        if (!optional.isPresent()){
            throw new ValidationException("密钥不存在");
        }
        //权限校验
        checkPermission();
        secretsRepository.deleteById(uuid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SecretsBean recoveryLogicalDelKey(String uuid) {
        //参数校验
        if (StringUtils.isEmpty(uuid)){
            throw new ValidationException("密钥不存在");
        }
        Optional<SecretsBean> optional = secretsRepository.findById(uuid);
        if (!optional.isPresent()){
            throw new ValidationException("密钥不存在");
        }
        //权限校验
        checkPermission();
        SecretsBean secretsBean = optional.get();
        secretsBean.setDeleted(false);
        secretsRepository.saveAndFlush(secretsBean);
        return secretsBean;
    }

    @Override
    public Page searchLogicalDelKey(PageRequestDate pageRequestDate, SecretsBean searchParams) {
        checkPermission();
        //进行分页设置
        return secretsRepository.findAll((Specification<SecretsBean>) (root, query, cb) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(cb.equal(root.get("deleted").as(Boolean.class), true));
            //TODO 查询条件
            if (StringUtils.isNotBlank(searchParams.getName())) {
                list.add(cb.like(root.get("name").as(String.class), "%" + searchParams.getName().trim() + "%"));
            }
            if (StringUtils.isNotBlank(searchParams.getAlgorithm())) {
                list.add(cb.like(root.get("algorithm").as(String.class), "%" + searchParams.getAlgorithm().trim() + "%"));
            }
            if (StringUtils.isNotBlank(searchParams.getMode())) {
                list.add(cb.like(root.get("mode").as(String.class), "%" + searchParams.getMode().trim() + "%"));
            }
            if (StringUtils.isNotBlank(searchParams.getBitLength())) {
                list.add(cb.equal(root.get("bitLength").as(String.class), searchParams.getBitLength().trim()));
            }
            if (StringUtils.isNotBlank(searchParams.getSecretType())) {
                list.add(cb.equal(root.get("secretType").as(String.class), searchParams.getSecretType().trim()));
            }
            if (StringUtils.isNotEmpty(searchParams.getCreatedTimeBegin())) {
                list.add(cb.greaterThanOrEqualTo(root.get("createdTime").as(String.class), searchParams.getCreatedTimeBegin().trim()));
            }
            if (StringUtils.isNotEmpty(searchParams.getCreatedTimeEnd())) {
                list.add(cb.lessThanOrEqualTo(root.get("createdTime").as(String.class), searchParams.getCreatedTimeEnd().trim()));
            }
            Predicate[] p = new Predicate[list.size()];
            return cb.and(list.toArray(p));
        }, pageRequestDate.getPageRequest());

    }

    public void checkPermission(){
        SysUserBean loginUser = sysUserService.findLoginSysUser();
        if (loginUser == null) {
            throw new UserInfoInVaildException();
        }
        if(!SysUserBean.USER_TYPE_ADMIN.equalsIgnoreCase(loginUser.getUserType())){
            throw new UserInfoInVaildException();
        }
    }
}
